#ifndef PAT_H
#define PAT_H

#ifdef __cplusplus
extern "C"
{
#endif

/*****************************************************************************
 * Program Association Table
 *****************************************************************************/
#define PAT_PID                 SI_PID_PAT
#define PAT_TABLE_ID            SI_TID_PAT
#define PAT_HEADER_SIZE         SI_HEADER_SIZE_SYNTAX1
#define PAT_PROGRAM_SIZE        4

static inline ms_u16 pat_get_sectionLen(ms_byte n)
{
	//负载偏移+HEADER+负载--0x000D
	return (1+PAT_HEADER_SIZE+n*PAT_PROGRAM_SIZE);
}
static inline ms_byte *pat_get_program(ms_byte *p_pat, ms_u16 n)
{
    ms_byte *p_pat_n = p_pat + PAT_HEADER_SIZE + n * PAT_PROGRAM_SIZE;
    return p_pat_n;
}
static inline ms_s32 pat_api_build( ms_byte * ptspkt,ms_u08 *cc,ms_u08 size,ms_byte adaption_field_control,
	ms_u16 transport_stream_id,PATPARAMContxt *pat_ctt)
{
	ms_byte ptspkt_tmp[1024]={0};
//构建PAT的TS头 
	//mssi_api_tsInit(ptspkt_tmp,PAT_PID,(*cc), size,adaption_field_control,0x01);
//查找PAT数据位置
	ms_u16 section_len=pat_get_sectionLen(pat_ctt->totalnum);
	ms_byte *pTsPkt_pat=mssi_api_setAdaptationFieldLen(adaption_field_control, section_len, ptspkt_tmp,0);
	if(ms_null==pTsPkt_pat){
		return 0;
	}	
	
//第一字节填0：1字节		
	pTsPkt_pat[0]=0x00;
	ms_byte *p_pat=&pTsPkt_pat[1];
	
//构建SYNTAX1头部：8字节		
	mssi_api_buildSyntax1Head(p_pat, PAT_TABLE_ID, section_len, transport_stream_id,0,0,0);

//构建节目：totalnum*4字节		 
	for(ms_u16 index=0;index<pat_ctt->totalnum;index++){
		ms_byte *p_pat_n=pat_get_program(p_pat, index);
		//program_num	
		if(p_pat_n){		
			ms_network_2b(p_pat_n, pat_ctt->serviceidList[index]);
		//res	
			p_pat_n[2]=(0x07<<5)&0xE0;	
		//programid
			p_pat_n[2]|=((pat_ctt->pmtIdList[index]>>8)&0x1f);
			p_pat_n[3]=pat_ctt->pmtIdList[index]&0xFF;	
		}		
	}	
//构建CRC：4字节	
	ms_u32 crc=mscrc_api_CRC32(p_pat, (section_len-1));
	ms_network_4b((&pTsPkt_pat[section_len]), crc);

	ms_u08 cc_real=(*cc);
	ms_u16 numTs=(section_len+SI_CRCLEN)/TS_SIZE_PES;
	if((section_len+SI_CRCLEN)%TS_SIZE_PES){
		numTs+=1;
	}
	for(ms_u16 index=0;index<numTs;index++){
		if(!index){
			mssi_api_tsInit(&ptspkt[index*size],PAT_PID,cc_real, size,adaption_field_control,0x01);
		}else{
			mssi_api_tsInit(&ptspkt[index*size],PAT_PID,cc_real, size,adaption_field_control,0x00);
		}
		if(++cc_real>0XF){
			cc_real=0;
		}
		ms_byte *src=&ptspkt_tmp[index*TS_SIZE_PES+TS_SIZE_HEADER];
		ms_byte *dst=&ptspkt[index*size+TS_SIZE_HEADER];
		ms_memcpy(dst, src, TS_SIZE_PES);
	}
	(*cc)=cc_real;
	return (numTs*size);
}
	
#ifdef __cplusplus
}
#endif

#endif
